﻿using System.Security.Cryptography.X509Certificates;
using AutoMapper;
using B.S.DataBase.MyProject.Domain.Procurements;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Read.API.Applicantions.Command.ProcurementsCommand;
using T.E.ERP.Read.API.Dtos.Dtos;

namespace T.E.ERP.Read.API.Applicantions.CommandHandler.ProcurementsCommandCommand
{
    /// <summary>
    /// 采购部门查询
    /// </summary>
    public class PurchasingCommmandHander : IRequestHandler<PurchasingCommmand, APIResult<List<PurchasingDtos>>>
    {
        /// <summary>
        /// 采购部门表
        /// </summary>

        private readonly IBaseRepository<Purchasing> baseRepository;


        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository"></param>
        public PurchasingCommmandHander(IBaseRepository<Purchasing> repository, IMapper mapper)
        {
            baseRepository = repository;
            this.mapper = mapper;
        }

        /// <summary>
        ///处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<List<PurchasingDtos>>> Handle(PurchasingCommmand request, CancellationToken cancellationToken)
        {

            
            APIResult<List<PurchasingDtos>> result = new APIResult<List<PurchasingDtos>>();

            var model = baseRepository.GetAll();
            result.Code = APIEnum.成功;
            result.Msg = APIEnum.查询成功.ToString();
            result.data = GetPurchasings(0);
            return Task.FromResult(result);
        }

        public List<PurchasingDtos> GetPurchasings(int Purchasinglevel)
        {
            var depa = baseRepository.GetAll().Result.Where(X => X.Purchasinglevel == Purchasinglevel);
            var dto = mapper.Map<List<PurchasingDtos>>(depa);

            foreach (var item in dto)
            {
                item.Children = GetPurchasings(item.Purchasingid);
            }
            return dto;

        }
    }
}
